const PROMISE_STATUS_PENDING = "pending"
const PROMISE_STATUS_FULFILLED = "fulfilled"
const PROMISE_STATUS_REJECTED = "rejected"

class XJPromise {
  // 构造函数方法
  constructor(executor) {
    // 刚进入的时候当前状态
    this.status = PROMISE_STATUS_PENDING
    this.value = undefined //用于保存resolve的参数值，用于then方法中的回调显示
    this.reason = undefined

    const resolve = (value) => {
      if (this.status === PROMISE_STATUS_PENDING) {
        setTimeout(() => {
          //通过setTimeOut，让这段代码进入宏任务队列，这样，then方法就可以先执行了，不然调用then中的回调，
          // then方法都不存在呢，更别说then方法中的回调调用了
          this.status === PROMISE_STATUS_FULFILLED
          this.reason = value
          console.log("resolve别调用了")
          //接下来应该调用then传递过来的回调函数
          this.onfulfilled(value)
        }, 0)
      }
    }
    const reject = (reason) => {
      if (this.status === PROMISE_STATUS_PENDING) {
        this.status === PROMISE_STATUS_REJECTED
        this.reason = reason
      }
    }

    executor(resolve, reject) //执行器函数直接调用
  }

  //实例方法- then方法
  then(onfulfilled, onrejected) {
    this.onfulfilled = onfulfilled
    this.onrejected = onrejected
  }
}

// 调用
new XJPromise((resolve, reject) => {
  console.log("当前还处于pending状态")
  resolve("resolve")
}).then(
  (res) => {
    console.log("res", res)
  },
  (err) => {}
)
